package com.guodaxia.gzh.tools;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;


@Slf4j
@Controller
@RequestMapping("/excel")
public class UploadExcelController {

    //注入监听器
/*
    @Autowired
    private EmployeeReadListener listener;
*/


    /**
     * 获得前端上传的文件  EasyExcel.read 需要传入三个参数 文件流 操作实体类的字节码 监听器
     *
     * @return 0 成功上传
     * @throws IOException
     */
    @RequestMapping("/read")
    @ResponseBody
    public String readExcel() throws IOException {
        //MultipartFile file
        long start = System.currentTimeMillis();


//        ExcelListener excelListener = new ExcelListener();
        // 得到excel读取对象  //通过文件获得流， 获得读取文件的class    填入监听器 监听器每读取一行就执行一次新增
//        ExcelReaderBuilder read = EasyExcel.read(Files.newInputStream(new File("d:\\企业数据.xlsx").toPath()), EmployeeBo.class, excelListener);
        //获取表格
        ExcelReaderBuilder read = EasyExcel.read(new File("d:\\\\企业数据.xlsx"));
        ExcelReaderSheetBuilder sheet = read.sheet(0);
        //读取表格
        sheet.doRead();
        long end = System.currentTimeMillis();
        log.info("解析100万数据耗时:{}s", (end - start) / 1000);
        return "已成功导入";
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();

        List<EmployeeBo> list = new ArrayList<>();
        Consumer<List<EmployeeBo>> employeeBoConsumer = employeeBos -> list.addAll(employeeBos);
        ExcelReaderBuilder read = EasyExcel.read("d:\\企业数据.xlsx", EmployeeBo.class, new PageReadListener<EmployeeBo>(employeeBoConsumer));
        ExcelReaderSheetBuilder sheet = read.sheet(0);
        //读取表格
        sheet.doRead();
        long end = System.currentTimeMillis();
        log.info("解析100万数据耗时:{}s", (end - start) / 1000);
  /*      for (EmployeeBo employeeBo : list) {
            System.out.println(employeeBo);
        }*/
        System.out.println(list.size());
    }

    @RequestMapping("/write")
    public void writeExcel(HttpServletResponse response) throws IOException {
        //设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //导出的文件名
        String filename = URLEncoder.encode("员工信息", "utf-8");
        //设置响应头
        response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xlsx");
        //获得流对象
        ServletOutputStream outputStream = response.getOutputStream();
        //获得write对象
        ExcelWriterBuilder write = EasyExcel.write(outputStream, EmployeeBo.class);
        //获得数据表对象
        ExcelWriterSheetBuilder sheet = write.sheet();
        //准备需要输出的数据   调用业务层，获得所有需要导出的数据
        List<EmployeeBo> list = getMockData();
        //生成表格文件
        sheet.doWrite(list);
    }

    /**
     * mock 100万数据
     *
     * @return
     */
    private List<EmployeeBo> getMockData() {
        List<EmployeeBo> dataList = new ArrayList<>();

        for (int i = 0; i < 3; i++) {
            EmployeeBo employeeBo = new EmployeeBo();
            employeeBo.setOutEid(getVerificationCode(6));
            employeeBo.setOutAid(getVerificationCode(4));
            employeeBo.setOutUserId(getVerificationCode(10));
            employeeBo.setInEid(getVerificationCode(6));
            employeeBo.setInAid(getVerificationCode(4));
            employeeBo.setInUserId(getVerificationCode(10));
            dataList.add(employeeBo);
        }

        return dataList;
    }


    /**
     * 生成验证码：字母+数字
     *
     * @param length 验证码长度
     * @return 验证码字符串
     */
    public static String getVerificationCode(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder verificationCode = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            verificationCode.append(characters.charAt(index));
        }

        return verificationCode.toString();
    }


}
 